package com.orion.config;

/**
 * @author Administrator
 * @date 2021/9/13
 */

import com.orion.exception.VerfifyCodeException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpMethod;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * 继承一个过滤器，实现验证码验证
 */
public class AjaxVerifyCodeFilter extends OncePerRequestFilter {

    private static final AntPathRequestMatcher ANT_PATH_REQUEST_MATCHER = new AntPathRequestMatcher("/haha", HttpMethod.POST.name());

    private AuthenticationFailureHandler authenticationFailureHandler;

    public AjaxVerifyCodeFilter(AuthenticationFailureHandler authenticationFailureHandler) {
        this.authenticationFailureHandler = authenticationFailureHandler;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        RequestMatcher.MatchResult matcher = ANT_PATH_REQUEST_MATCHER.matcher(httpServletRequest);
        if (matcher.isMatch()) {
            try {
                validate(httpServletRequest);
            } catch (VerfifyCodeException e) {
                this.authenticationFailureHandler.onAuthenticationFailure(httpServletRequest, httpServletResponse, e);
                return;
            }
        }
        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }

    private void validate(HttpServletRequest httpServletRequest) {


        String inputVerifyCode = httpServletRequest.getParameter("verifyCode");

        if (StringUtils.isBlank(inputVerifyCode)) {
            throw new VerfifyCodeException("验证码为空");
        }

        Object attrObj = httpServletRequest.getSession().getAttribute("verifyCode");
        if (Objects.isNull(attrObj) || attrObj.toString().isEmpty()) {
            throw new VerfifyCodeException("验证码已过期");
        }

        String sessionVerifyCode = attrObj.toString();
        if (!inputVerifyCode.equalsIgnoreCase(sessionVerifyCode)) {
            throw new VerfifyCodeException("验证码不正确");
        }
    }
    public AuthenticationFailureHandler getAuthenticationFailureHandler() {
        return authenticationFailureHandler;
    }

    public void setAuthenticationFailureHandler(AuthenticationFailureHandler authenticationFailureHandler) {
        this.authenticationFailureHandler = authenticationFailureHandler;
    }
}


